﻿using log4net;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Management;

namespace WindowsInfoTool
{
    public partial class WindowsFrm : Form
    {
        private static ILog _log = LogManager.GetLogger(typeof(WindowsFrm));
        public WindowsFrm()
        {
            InitializeComponent();
            dgv_data.AllowUserToAddRows = false;
            dgv_data.AutoResizeColumns();
            dgv_data.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            //不允许为多行选中
            dgv_data.MultiSelect = false;
        }
        int count = 0;
        string zhuangtai = "";
        Process[] myProcess;
        public string fileName;
        public string Name;   
        private void WindowsFrm_Load(object sender, EventArgs e)
        {
            this.Left = (int)((Screen.PrimaryScreen.Bounds.Width - this.Width) / 2);
            this.Top = (int)((Screen.PrimaryScreen.Bounds.Height - this.Height) / 2);
            #region 这是遍历计算机硬盘并输出硬盘的序列号
            //创建ManagementObjectSearcher对象
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
            String strHardDiskID = null;//存储磁盘序列号
            //调用ManagementObjectSearcher类的Get方法取得硬盘序列号
            foreach (ManagementObject mo in searcher.Get())
            {
                strHardDiskID = mo["SerialNumber"].ToString().Trim();//记录获得的磁盘序列号
                break;
            }
            toolStripStatusLabel2.Text = "硬盘序列号为： " + strHardDiskID;//显示硬盘序列号     
            #endregion
        }
        /// <summary>
        /// 执行按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void but_Click(object sender, EventArgs e)
        {
            Process p = new Process();
            //Process类有一个StartInfo属性，这个是ProcessStartInfo类，包括了一些属性和方法，下面我们用到了他的几个属性：

            p.StartInfo.FileName = "cmd.exe";
            if (radioButton1.Checked == true)
            {
                // p.StartInfo.Arguments = "/c winver";
                p.StartInfo.Arguments = "/c ipconfig /all";
            }
            if (radioButton2.Checked == true)
            {
                p.StartInfo.Arguments = "/c ping 127.0.0.1";
            }
            if (radioButton3.Checked == true)
            {
                if (time.Text != "" && count == 0)
                {
                    count++;
                    string shijian = time.Text;
                    p.StartInfo.Arguments = string.Format("/c shutdown -s -t {0}", shijian);
                    zhuangtai = "a";
                }
                else
                {
                    if (count != 0)
                    {
                        MessageBox.Show("系统已经设置了自动关机时间。", "友情提醒", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        zhuangtai = "";
                    }
                    else
                    {
                        MessageBox.Show("请输入时间,以秒为单位。", "友情提醒", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        zhuangtai = "";
                    }
                    return;
                }
            }
            if (radioButton4.Checked == true)
            {
                if (count > 0)
                {
                    count--;
                    p.StartInfo.Arguments = "/c shutdown -a";
                    zhuangtai = "b";
                }
                else
                {
                    MessageBox.Show("系统没有设置自动关机时间，所以无法注销。", "友情提醒", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    zhuangtai = "";
                }
            }
            if (radioButton5.Checked == true)
            {
                if (dns.Text != "")
                {
                    string yuming = dns.Text;
                    p.StartInfo.Arguments = string.Format("/c ping {0}", yuming);
                }
                else
                {
                    MessageBox.Show("请输入合法的域名，谢谢。", "友情提醒", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            if (radioButton6.Checked == true)
            {
                if (ip.Text != "")
                {
                    string ipaddress = ip.Text;
                    p.StartInfo.Arguments = string.Format("/c ping {0}", ipaddress);
                }
                else
                {
                    MessageBox.Show("请输入合法的ip地址，谢谢。", "友情提醒", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            if (radioButton7.Checked == true)
            {
                p.StartInfo.Arguments = "/c  netstat -an";
            }
            if (radioButton8.Checked == true)
            {
                p.StartInfo.Arguments = "/c  netstat -r";
            }
            if (radioButton9.Checked == true)
            {
                p.StartInfo.Arguments = "/c winver";
            }
            if (radioButton10.Checked == true)
            {
                p.StartInfo.Arguments = "/c  Nslookup";
            }
            if (radioButton11.Checked == true)
            {
                p.StartInfo.Arguments = "/c  cleanmgr";
            }
            if (radioButton12.Checked == true)
            {
                p.StartInfo.Arguments = "/c  regedit";
            }
            //p.StartInfo.Arguments = "/c ping 127.0.0.1" ;    //设定程式执行参数
            p.StartInfo.UseShellExecute = false;               //关闭Shell的使用
            p.StartInfo.RedirectStandardInput = true;          //重定向标准输入
            p.StartInfo.RedirectStandardOutput = true;         //重定向标准输出
            p.StartInfo.RedirectStandardError = true;          //重定向错误输出
            p.StartInfo.CreateNoWindow = true;                 //设置不显示窗口
            p.Start();                                         //启动
            p.StandardInput.WriteLine("exit");                 //不过要记得加上Exit要不然下一行程式执行的时候会当机
            if (radioButton3.Checked == true && zhuangtai == "a")
            {
                int miao = Convert.ToInt32(time.Text) / 60;

                xianshi.Text = string.Format("您的计算机将在{0}分钟后自动关机", miao);
            }
            else if (radioButton4.Checked == true && zhuangtai == "b")
            {
                xianshi.Text = "您取消了自动关机";
            }

            else
            {
                xianshi.Text = p.StandardOutput.ReadToEnd();
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            //Application.Exit();
            this.Close();
        }
        #region radioButton触发的事件
        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            xianshi.Text = "";
            time.Text = "";
            dns.Text = "";
            ip.Text = "";
        }

        private void radioButton9_CheckedChanged(object sender, EventArgs e)
        {
            xianshi.Text = "";
            time.Text = "";
            dns.Text = "";
            ip.Text = "";
        }

        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            xianshi.Text = "";
            time.Text = "";
            dns.Text = "";
            ip.Text = "";
        }

        private void radioButton6_CheckedChanged(object sender, EventArgs e)
        {
            xianshi.Text = "";
            time.Text = "";
            dns.Text = "";
            ip.Text = "";
        }

        private void radioButton5_CheckedChanged(object sender, EventArgs e)
        {
            xianshi.Text = "";
            time.Text = "";
            dns.Text = "";
            ip.Text = "";
        }

        private void radioButton8_CheckedChanged(object sender, EventArgs e)
        {
            xianshi.Text = "";
            time.Text = "";
            dns.Text = "";
            ip.Text = "";
        }

        private void radioButton4_CheckedChanged(object sender, EventArgs e)
        {
            xianshi.Text = "";
            time.Text = "";
            dns.Text = "";
            ip.Text = "";
        }

        private void radioButton11_CheckedChanged(object sender, EventArgs e)
        {
            xianshi.Text = "";
            time.Text = "";
            dns.Text = "";
            ip.Text = "";
        }

        private void radioButton7_CheckedChanged(object sender, EventArgs e)
        {
            xianshi.Text = "";
            time.Text = "";
            dns.Text = "";
            ip.Text = "";
        }

        private void radioButton12_CheckedChanged(object sender, EventArgs e)
        {
            xianshi.Text = "";
            time.Text = "";
            dns.Text = "";
            ip.Text = "";
        }

        private void radioButton10_CheckedChanged(object sender, EventArgs e)
        {
            xianshi.Text = "";
            time.Text = "";
            dns.Text = "";
            ip.Text = "";
        }

        private void radioButton3_CheckedChanged(object sender, EventArgs e)
        {
            xianshi.Text = "";
            time.Text = "";
            dns.Text = "";
            ip.Text = "";
        }
        #endregion
        private void timer1_Tick(object sender, EventArgs e)
        {
            this.toolStripStatusLabel1.Text = "欢迎使用本软件" + "当前时间为：" + DateTime.Now.ToString("yyyy-MM-dd ") + DateTime.Now.ToLongTimeString(); //状态栏显示当前时间
        }
        #region 计算机进程查询窗体的代码
        /// <summary>
        /// 获取计算机程序进程
        /// </summary>
        private void GetMyComputerProcess()
        {
            try
            {
                this.BeginInvoke(new Action(() =>
                {
                    dgv_data.Rows.Clear();
                    myProcess = Process.GetProcesses();
                    foreach (Process p in myProcess)
                    {
                        int nerRowIndex = dgv_data.Rows.Add();
                        DataGridViewRow row = dgv_data.Rows[nerRowIndex];
                        row.Cells[0].Value = p.Id;
                        row.Cells[1].Value = p.ProcessName;
                        //显示单位为MB，故除去两个1024.0
                        row.Cells[2].Value = string.Format("{0:###,##0.00}MB", p.WorkingSet64 / 1024.0f / 1024.0f);
                        try
                        {
                            row.Cells[3].Value = string.Format("{0}", p.StartTime);
                            row.Cells[4].Value = p.MainModule.FileName;
                        }
                        catch (Exception)
                        {
                            row.Cells[3].Value = "";
                            row.Cells[4].Value = "";
                        }
                    }
                }));
            }
            catch (Exception ex)
            {
                _log.Error(ex.ToString());
            }
        }
        /// <summary>
        /// 显示进程信息
        /// </summary>
        /// <param name="p"></param>
        private void ShowProcessInfo(Process p)
        {
            //建立可变字符串，存放进程信息
            StringBuilder sb = new StringBuilder();
            sb.Append("进程名称：" + p.ProcessName + ",  ID:" + p.Id);
            //获取选取进程的名称
            Name = p.ProcessName;
            try
            {
                sb.AppendLine("进程优先级：" + p.BasePriority + "(优先级类别：" + p.PriorityClass + ")");
                ProcessModule m = p.MainModule;
                fileName = m.FileName;
                sb.AppendLine("文件名：" + m.FileName);
                sb.AppendLine("版本：" + m.FileVersionInfo.FileVersion);
                sb.AppendLine("描述：" + m.FileVersionInfo.FileDescription);
                sb.AppendLine("语言：" + m.FileVersionInfo.Language);
                sb.AppendLine("___________________________________");
                if (p.Modules != null)
                {
                    ProcessModuleCollection pmc = p.Modules;
                    sb.AppendLine("调用的模块（.DLL）");
                    for (int i = 0; i < pmc.Count; i++)
                    {
                        sb.AppendLine("模块名：" + pmc[i].ModuleName + "\t" +
                            "版本：" + pmc[i].FileVersionInfo.FileVersion + "\t" +
                            "描述:" + pmc[i].FileVersionInfo.FileDescription);
                    }
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.ToString());
                sb.AppendLine("其他信息无法读取！！！");
            }
            richTextBox1.Text = sb.ToString();
        }
        /// <summary>
        /// 停止进程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void but_Stop_Click(object sender, EventArgs e)
        {
            CloseApp(textBox1.Text);
        }
        /// <summary>
        /// 停止进程
        /// </summary>
        /// <param name="ArrayProcessName"></param>
        private void CloseApp(string ArrayProcessName)
        {
            string[] processName = ArrayProcessName.Split(',');
            foreach (string appName in processName)
            {
                Process[] localApp = Process.GetProcessesByName(appName);
                if (localApp.Length > 0)
                {
                    foreach (var app in localApp)
                    {
                        if (!app.HasExited)
                        {
                            app.Kill();//关闭进程
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 退出程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Close_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        /// <summary>
        /// 数据显示鼠标点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgv_data_MouseClick(object sender, MouseEventArgs e)
        {
            DataGridView.HitTestInfo h = dgv_data.HitTest(e.X, e.Y);
            if (h.Type == DataGridViewHitTestType.RowHeader || h.Type == DataGridViewHitTestType.Cell)
            {
                dgv_data.Rows[h.RowIndex].Selected = true;
                int processId = (int)dgv_data.CurrentRow.Cells[0].Value;
                ShowProcessInfo(Process.GetProcessById(processId));
                label1.Text = fileName;
                textBox1.Text = Name;
            }
        }
        Thread _getMyComputerProcess;
        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Restart_Click(object sender, EventArgs e)
        {
            //_getMyComputerProcess = new Thread(new ThreadStart(GetMyComputerProcess));
            //_getMyComputerProcess.Start();
            GetMyComputerProcess();
        }
        #endregion
    }
}
